package com.ja.openchat.ui.chat.group;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityEditGroupChatBinding;
import com.ja.openchat.ui.chat.group.adapter.MemberGridAdapter;
import com.ja.openchat.ui.contact.ContactChooseActivity;
import com.ja.openchat.ui.contact.ContactDetailActivity;
import com.ja.openchat.ui.contact.ContactDetailSingleActivity;
import com.ja.openchat.ui.me.PersonalDataFragment;
import com.ja.openchat.viewmodels.EditGroupViewModel;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.GroupMemberInfo;
import com.zy.openchat.core.model.group.SuperGroupFullInfo;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.MediaUtils;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseActivity;

public class EditGroupChatActivity extends BaseActivity<ActivityEditGroupChatBinding,EditGroupViewModel> implements View.OnClickListener {


    public static void start(Activity activity,String announcement,ChatInfo chat) {
        Intent intent = new Intent();
        intent.setClass(activity, EditGroupChatActivity.class);
        intent.putExtra("chat", chat);
        intent.putExtra("announcement", announcement);
        activity.startActivity(intent);
    }

    private String annContentStr = null;
    private String noticeTextStr = null;
    public ChatInfo chatInfo;
    public SuperGroupInfo super_groupInfo;
    public SuperGroupFullInfo super_groupFullInfo;
    //群成员列表
    private List<GroupMemberInfo> orgi_membersList = new ArrayList<>();
    private List<GroupMemberInfo> membersList = new ArrayList<>();
    //群管理员列表
    private List<GroupMemberInfo> orgi_memberIsManagersList = new ArrayList<>();
    private List<GroupMemberInfo> memberIsManagersList = new ArrayList<>();
    public MemberGridAdapter memberIsManagerGridAdapter;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_edit_group_chat;
    }


    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public EditGroupViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(EditGroupViewModel.class);
    }

    @Override
    public void initView() {
        super.initView();
        binding.toolbar.tvBarTitle.setText(getString(R.string.edit_group));
        binding.toolbar.tvOkRight.setText(getString(R.string.finish_text));
        binding.toolbar.tvOkRight.setVisibility(View.VISIBLE);
        binding.toolbar.tvOkRight.setBackground(ContextCompat.getDrawable(this,R.drawable.transparent_shape));
        binding.toolbar.tvOkRight.setTextColor(ContextCompat.getColor(this,R.color.nav_btn_bg));
        if (getIntent() != null) {
            chatInfo = getIntent().getParcelableExtra("chat");
            annContentStr = getIntent().getStringExtra("announcement");
        } else {
            chatInfo = new ChatInfo();
        }

        this.binding.headerImageView.setTextSize(20);
        viewModel.setContext(this,binding);
        binding.toolbar.ivBarBack.setOnClickListener(this);
        binding.userAvatarLayout.setOnClickListener(this);
        binding.managerLayout.setOnClickListener(this);
        binding.noticeText.setOnClickListener(this);
        binding.nameLayout.setOnClickListener(this);
        binding.groupNoticeLayout.setOnClickListener(this);
        binding.toolbar.tvOkRight.setOnClickListener(this);
        binding.groupAnnLayout.setOnClickListener(this);
        binding.groupAnnTitle.setOnClickListener(this);
        binding.annContent.setOnClickListener(this);
        //初始化列表
        memberListUI();
        //刷新UI
        syncChatInfo();
        //检查状态
        checkUserChatState();
        syncFullGroupInfo();
    }

   public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_avatar_layout:
                if (canEditGroupSetting()) {
                    //设置群组头像
                    MediaUtils.choosePhoto(this, true);
                }
                break;
            case R.id.noticeText://群简介
            case R.id.group_notice_layout:
                ModifyFieldActivity.start_setGroupSummary(this, chatInfo.id, noticeTextStr,true);
                break;
            case R.id.nameLayout:
                ModifyFieldActivity.start_setGroupName(this, chatInfo.id, binding.nameText.getText().toString());
                break;
            case R.id.managerLayout://权限管理
                GroupChatManagerActivity.start(this, chatInfo);
                break;
            case R.id.iv_bar_back:
                finish();
                break;
            case R.id.group_ann_layout:
            case R.id.group_ann_title:
            case R.id.ann_content:
                //设置群组公告
                ModifyFieldActivity.start_setGroupNotice(this, chatInfo.id, annContentStr,true);
                break;
            case R.id.tv_ok_right:
                if(TextUtils.isEmpty(binding.nameText.getText())){
                    ToastUtils.showShort(getString(R.string.input_group_name));
                    return;
                }
//                if(TextUtils.isEmpty(noticeText.getText())){
//                    ToastUtils.showShort("请输入群简介");
//                    return;
//                }
                isCompleteSave = false;
                isCompleteSet = false;
                saveGroupName(binding.nameText.getText().toString());
                setGroupPinnedMessage_step1(binding.noticeText.getText().toString());
                break;
        }
    }

    public void resetUI(){
        binding.headerImageView.showGroup(chatInfo);
        binding.nameText.setText(chatInfo.title);
    }
    private boolean isRequestsyncFullGroupInfo = false;
    @Override
    protected void onResume() {
        super.onResume();
        //显示群通知
        resetNoticeInfo();
        //同步群通知
        syncGroupNotice();
        if(!isRequestsyncFullGroupInfo){
            syncFullGroupInfo();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isRequestsyncFullGroupInfo = false;
    }

    private MessageInfo lastPinnedMsg;
    private void syncGroupNotice() {
        TelegramManager.getTelegramManager().getGroupNotice(this, chatInfo.id, new TgResultBlock<MessageInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, MessageInfo obj) {
                if (obj != null) {
                    lastPinnedMsg = obj;
                    resetNoticeInfo();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    //群通知
    private void resetNoticeInfo() {
        if (lastPinnedMsg != null) {
            String text = lastPinnedMsg.toString();
            if (text.startsWith(Constants.GROUP_NOTICE_PREFIX)) {
                text = text.substring(Constants.GROUP_NOTICE_PREFIX.length());
            }else if(text.startsWith(Constants.GROUP_NOTICE_PREFIX.trim())){
                text = text.substring(Constants.GROUP_NOTICE_PREFIX.trim().length());
            }
            binding.noticeText.setText(text);
        } else {
            binding.noticeText.setText("");
        }
    }


    private void syncChatInfo() {
        if (chatInfo != null) {
            ChatInfo chat = TelegramManager.getTelegramManager().getTgData().chatInfo(chatInfo.id);
            if (chat != null) {
                chatInfo = chat;
            }
        }
        resetUI();
    }

    private void memberListUI() {
        //管理员列表
        GridLayoutManager layoutManager = new GridLayoutManager(this, 5);
        layoutManager.setOrientation(GridLayoutManager.VERTICAL);
        binding.managerRecyclerView.setLayoutManager(layoutManager);
        memberIsManagerGridAdapter = new MemberGridAdapter(R.layout.adapter_grid_member, memberIsManagersList);
        binding.managerRecyclerView.setAdapter(memberIsManagerGridAdapter);
        memberIsManagerGridAdapter.setOnItemClickListener((adapter, view1, position) -> {
            GroupMemberInfo member = memberIsManagersList.get(position);
            clickMember(member, true);
        });
    }

    private void clickMember(GroupMemberInfo member, boolean isManager) {
        if (member.isOptAdd()) {
            if (isManager) {//增加管理员
                ContactChooseActivity.startWithAddManager(this, chatInfo.id, orgi_membersList, orgi_memberIsManagersList);
            } else {//增加成员
                ContactChooseActivity.startWithInviteMember(this, chatInfo.id, orgi_membersList);
            }
        } else if (member.isOptDel()) {
            if (isManager) {//删除管理员
                ContactChooseActivity.startWithRemoveManager(this, chatInfo.id, orgi_memberIsManagersList);
            } else {//删除成员
                ContactChooseActivity.startWithRemoveMember(this, chatInfo.id, orgi_membersList, orgi_memberIsManagersList);
            }
        } else {
            UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(member.user_id);
            if (user == null) return;
            if (member.user_id == UserInfo.getUserInfo().id) {
//                ProfileActivity.start(this);
                startContainerActivity(PersonalDataFragment.class.getCanonicalName());
            } else {
                if (super_groupInfo != null && super_groupInfo.status != null) {
                    TelegramManager.GroupMemberState state = super_groupInfo.status.getMemberState();
                    if (state == TelegramManager.GroupMemberState.GroupMemberState_Administrator || state == TelegramManager.GroupMemberState.GroupMemberState_Creator) {
//                        ContactDetailActivity.start(this, user, chatInfo.id, true);
                        ContactDetailSingleActivity.start(this, user, chatInfo.id, true);
                    } else {
//                        ContactDetailActivity.start(this, user, !(chatInfo.permissions != null && !chatInfo.permissions.banWhisper));
                        ContactDetailSingleActivity.start(this, user, !(chatInfo.permissions != null && !chatInfo.permissions.banWhisper));
                    }
                } else {
//                    ContactDetailActivity.start(this, user, !(chatInfo.permissions != null && !chatInfo.permissions.banWhisper));
                    ContactDetailSingleActivity.start(this, user, !(chatInfo.permissions != null && !chatInfo.permissions.banWhisper));
                }
            }
        }
    }

    private void checkUserChatState() {
        TelegramManager.getTelegramManager().getSuperGroupInfo(this, chatInfo.superGroupId(), new TgResultBlock<SuperGroupInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, SuperGroupInfo obj) {
                if (obj != null) {
                    super_groupInfo = obj;
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    private void syncFullGroupInfo() {
        isRequestsyncFullGroupInfo = true;
        TelegramManager.getTelegramManager().getGroupNotice(this, chatInfo.id, new TgResultBlock<MessageInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, MessageInfo obj) {
                realRequestFullGroupInfo();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                realRequestFullGroupInfo();
            }
        });
    }

    private void realRequestFullGroupInfo(){
        TelegramManager.getTelegramManager().getSuperGroupFullInfo(this, chatInfo.superGroupId(), new TgResultBlock<SuperGroupFullInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, SuperGroupFullInfo obj) {
                if (obj != null) {
                    super_groupFullInfo = obj;
                    resetUI();
                    //获取超级群组成员列表
                    getSuperMembers();
                    //获取超级群组管理员列表
                    getSuperAdminMembers();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }


    public void resetMamagerMembersListUI() {
        memberIsManagersList.clear();
        int max = 15;
        if (canEditGroupManagerSetting()) max -= 2;
        for (int i = 0; i < orgi_memberIsManagersList.size() && i < max; i++) {
            memberIsManagersList.add(orgi_memberIsManagersList.get(i));
        }
        if (canEditGroupManagerSetting()) {
            memberIsManagersList.add(GroupMemberInfo.optAdd());
            memberIsManagersList.add(GroupMemberInfo.optDel());
        }
        memberIsManagerGridAdapter.notifyDataSetChanged();
    }

    public void getSuperMembers() {
        TelegramManager.getTelegramManager().getSuperGroupMembers(this, chatInfo.id,chatInfo.superGroupId(), "supergroupMembersFilterRecent", null, 0, 200, new TgResultBlock<List<GroupMemberInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                if (obj != null) {
                    orgi_membersList.clear();
                    if (obj.size() > 0) {
                        orgi_membersList.addAll(obj);
                    }
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    public void getSuperAdminMembers() {
        TelegramManager.getTelegramManager().getSuperGroupMembers(this,chatInfo.id, chatInfo.superGroupId(), "supergroupMembersFilterAdministrators", null, 0, 200, new TgResultBlock<List<GroupMemberInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                if (obj != null) {
                    orgi_memberIsManagersList.clear();
                    if (obj.size() > 0) {
                        orgi_memberIsManagersList.addAll(obj);
                    }
                    resetMamagerMembersListUI();
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    private boolean canInvideMember() {
        boolean canInvide = canEditGroupSetting();
        if (canInvide) {
            return canInvide;
        }
        return chatInfo.permissions != null && chatInfo.permissions.can_invite_users;
    }

    private boolean canEditGroupSetting() {
        if (super_groupInfo != null && super_groupInfo.status != null) {
            switch (super_groupInfo.status.getMemberState()) {
                case GroupMemberState_Administrator:
                    //管理员
                    return true;
                case GroupMemberState_Creator:
                    //创建者
                    if (super_groupInfo.status.is_member) {
                        return true;
                    }
                    break;
                case GroupMemberState_Left:
                    //不在群组
                    break;
                case GroupMemberState_Member:
                    //普通成员
                    break;
                case GroupMemberState_Banned:
                    //被禁用
                    break;
                case GroupMemberState_Restricted:
                    //被禁言
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    private boolean canEditGroupManagerSetting() {
        if (super_groupInfo != null && super_groupInfo.status != null) {
            switch (super_groupInfo.status.getMemberState()) {
                case GroupMemberState_Creator:
                    //创建者
                    if (super_groupInfo.status.is_member) {
                        return true;
                    }
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    private boolean isOwnerGroup() {
        if (super_groupInfo != null && super_groupInfo.status != null) {
            switch (super_groupInfo.status.getMemberState()) {
                case GroupMemberState_Creator:
                    //创建者
                    if (super_groupInfo.status.is_member) {
                        return true;
                    }
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<String> photos = MediaUtils.getResultAlbumData(this, requestCode, resultCode, data);
        if (photos != null && photos.size() > 0) {
            changeGroupHeader(photos.get(0));
        }
    }


    private void changeGroupHeader(String localPath) {
        showProgress();
        TelegramManager.getTelegramManager().setGroupPhoto(this, chatInfo.id, localPath, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private boolean isCompleteSave = false;
    private boolean isCompleteSet = false;

    private void saveGroupName(String name) {
        if (!StringUtils.isEmpty(name)) {
            showProgress();
            TelegramManager.getTelegramManager().setGroupName(this, chatInfo.id, name, new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    hideProgress();
                    if (obj.ok) {//设置成功
                        isCompleteSave = true;
                        if(isCompleteSave&&isCompleteSet){
                            finish();
                        }
//                        finish();
                    } else {
                        showErrorTip(getString(R.string.request_error) + obj.errString);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    showErrorTip(getString(R.string.request_error));
                }
            });
        }
//        else {
//            showWarnTip("请填写群组名称");
//        }
    }
    public MessageInfo sendingMsg;
    private void setGroupPinnedMessage_step1(String content) {
        //第一步，发送文本消息
        //第二步，设置为pinned消息
        if (!StringUtils.isEmpty(content)) {
            content = String.format("%s%s", Constants.GROUP_NOTICE_PREFIX, content);
            showProgress();
            TelegramManager.getTelegramManager().sendPinTextMessage(this, chatInfo.id, content, new TgResultBlock<MessageInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, MessageInfo obj) {
                    if (obj != null) {
                        if (obj.sendState() == TelegramManager.MessageSendState.MessageSendState_Success) {//发送成功
                            setGroupPinnedMessage_step2(obj.id);
                        } else if (obj.sendState() == TelegramManager.MessageSendState.MessageSendState_Pending) {//等待回调结果
                            hideProgress();
                            sendingMsg = obj;
                        } else {
                            hideProgress();
                            showErrorTip(getString(R.string.request_error));
                        }
                    } else {
                        hideProgress();
                        showErrorTip(getString(R.string.request_error));
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    showErrorTip(getString(R.string.request_error));
                }
            });
        }else{
            isCompleteSet = true;
        }
    }


    public void setGroupPinnedMessage_step2(long msgId) {
        TelegramManager.getTelegramManager().setGroupNotice(this, chatInfo.id, msgId, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip("群公告设置失败，请稍后重试, " + obj.errString);
                } else {
                    isCompleteSet = true;
                    if(isCompleteSave&&isCompleteSet){
                        finish();
                    }
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }
}
